package xworker.swt.dataObject.datastore;

import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.List;
import org.eclipse.swt.widgets.Listener;
import org.xmeta.ActionContext;
import org.xmeta.Thing;
import xworker.dataObject.DataObject;
import xworker.dataObject.DataStore;
import xworker.dataObject.DataStoreListener;

import java.util.Map;

public class ListDataStoreListener extends ControlDataStoreListener implements DataStoreListener, Listener {
    org.eclipse.swt.widgets.List list;

    public ListDataStoreListener(org.eclipse.swt.widgets.List list, DataStore dataStore, ActionContext actionContext){
        super(list, dataStore, actionContext);

        this.list = list;
        this.list.addListener(SWT.Selection, this);
        this.actionContext = actionContext;

        onReconfig(dataStore, dataStore.getDataObject());
        if(dataStore.isLoaded()){
            onLoaded(dataStore);
        }
    }

    public List getList() {
        return list;
    }

    @Override
    public void handleEvent(Event event) {
        this.clearSelection();

        int index = event.index;
        if(index < getAllItems().size()){
            this.addSelection(getAllItems().get(index));
        }
    }

    @Override
    public void onReconfig(DataStore dataStore, Thing dataObject) {
        exec(() -> list.removeAll());
    }

    @Override
    public void onLoaded(DataStore dataStore) {
        exec(() ->{
            list.removeAll();

            this.setAllItems(dataStore.getDatas());

            for(DataObject data : dataStore.getDatas()){
                list.add(data.getLabel());
            }

            selectionChanged();
        });
    }

    @Override
    public void onTotalCountUpdated(DataStore dataStore) {

    }

    @Override
    public void onChanged(DataStore dataStore) {
        onLoaded(dataStore);
    }

    @Override
    public void beforeLoad(DataStore dataStore, Thing condition, Map<String, Object> params) {
        exec(() -> list.removeAll());
    }

    @Override
    protected void selectionChanged() {
        if(getSelectedItems().size() > 0){
            DataObject data = getSelectedItems().get(0);
            int index = getAllItems().indexOf(data);
            if(index >= 0) {
                list.select(index);
            }
        }
    }
}
